package app.ep1.bandejoes;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import app.ep1.R;

public class EnviaInformacoesBandejaoActivity extends Activity {
	private String nomeBandejao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.envia_informacoes_bandejao);

		Bundle bundle = this.getIntent().getExtras();
		this.nomeBandejao = bundle.getString("nomeBandejao");

		Button confirma = (Button) findViewById(R.id.buttonConfirmaEnviaInformacoesBandejao);
		confirma.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				enviaOpiniao();
			}
		});
	}

	private void enviaOpiniao() {
		OpiniaoBandejao opiniaoBandejao = montaOpiniao();

		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(
				"http://valinhos.ime.usp.br:56080/usp-mobile/bandejao/"
						+ nomeBandejao);

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("comentario.fila",
				opiniaoBandejao.getFila().toString()));
		nameValuePairs.add(new BasicNameValuePair("comentario.texto",
				opiniaoBandejao.getTexto()));

		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		try {
			httpClient.execute(httpPost);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Intent resultIntent = new Intent();
		setResult(RESULT_OK, resultIntent);
		finish();
	}

	private OpiniaoBandejao montaOpiniao() {
		Spinner spinner = (Spinner) findViewById(R.id.spinnerTamanhoFilaBandejao);

		EditText texto = (EditText) findViewById(R.id.editTextEnviarComentarioBandejao);

		OpiniaoBandejao opiniao = new OpiniaoBandejao();
		opiniao.setTexto(texto.getText().toString());
		opiniao.setFila(spinner.getSelectedItem().toString());

		return opiniao;
	}
}
